package com.idea.dsl.template;

import com.idea.dsl.config.DslProperties;
import com.idea.dsl.model.DslRequest;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板管理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TemplateManager {
    
    private final DslProperties dslProperties;
    private final ResourceLoader resourceLoader;
    private Configuration freemarkerConfig;
    
    @PostConstruct
    public void init() {
        freemarkerConfig = new Configuration(Configuration.VERSION_2_3_32);
        freemarkerConfig.setDefaultEncoding("UTF-8");
        freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates/dsl");
    }
    
    /**
     * 生成提示词
     * 
     * @param request DSL请求
     * @return 生成的提示词
     */
    public String generatePrompt(DslRequest request) {
        try {
            String templateName = getTemplateName(request);
            Template template = freemarkerConfig.getTemplate(templateName);
            
            Map<String, Object> model = buildTemplateModel(request);
            
            StringWriter writer = new StringWriter();
            template.process(model, writer);
            
            String prompt = writer.toString();
            log.debug("生成的提示词: {}", prompt);
            
            return prompt;
            
        } catch (IOException | TemplateException e) {
            log.error("生成提示词失败", e);
            return buildDefaultPrompt(request);
        }
    }
    
    /**
     * 获取模板名称
     */
    private String getTemplateName(DslRequest request) {
        if (request.getTemplate() != null) {
            return request.getTemplate() + ".ftl";
        }
        
        return request.getDslType() + ".ftl";
    }
    
    /**
     * 构建模板模型
     */
    private Map<String, Object> buildTemplateModel(DslRequest request) {
        Map<String, Object> model = new HashMap<>();
        model.put("description", request.getDescription());
        model.put("dslType", request.getDslType());
        model.put("examples", request.getExamples());
        model.put("context", request.getContext());
        
        return model;
    }
    
    /**
     * 构建默认提示词
     */
    private String buildDefaultPrompt(DslRequest request) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请根据以下需求生成").append(request.getDslType()).append("格式的DSL:\n\n");
        prompt.append("需求描述: ").append(request.getDescription()).append("\n\n");
        
        if (request.getExamples() != null && !request.getExamples().isEmpty()) {
            prompt.append("参考示例:\n");
            for (int i = 0; i < request.getExamples().size(); i++) {
                prompt.append(i + 1).append(". ").append(request.getExamples().get(i)).append("\n");
            }
            prompt.append("\n");
        }
        
        if (request.getContext() != null && !request.getContext().isEmpty()) {
            prompt.append("上下文信息:\n");
            request.getContext().forEach((key, value) -> 
                prompt.append("- ").append(key).append(": ").append(value).append("\n"));
            prompt.append("\n");
        }
        
        prompt.append("请直接返回生成的DSL内容，不要包含其他说明文字。");
        
        return prompt.toString();
    }
    
    /**
     * 检查模板是否存在
     */
    public boolean templateExists(String templateName) {
        try {
            Resource resource = resourceLoader.getResource(
                dslProperties.getTemplates().getBasePath() + "/" + templateName + ".ftl");
            return resource.exists();
        } catch (Exception e) {
            return false;
        }
    }
}
